package com.example.API;

import com.example.Mapper.MessageMapper;
import com.example.Mapper.MessageSessionMapper;
import com.example.component.OnlineUserManager;
import com.example.pojo.Friend;
import com.example.pojo.Message;
import com.example.pojo.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;

import static java.lang.System.*;

@Component
public class WebSocketAPI extends TextWebSocketHandler {
    @Autowired
    private OnlineUserManager onlineUserManager;

    private ObjectMapper objectMapper = new ObjectMapper();

    @Resource
    private MessageSessionMapper messageSessionMapper;
    @Resource
    private MessageMapper messageMapper;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        out.println("websocket 连接成功!");
        try {
            User user = (User) session.getAttributes().get("user");
            onlineUserManager.oline(user.getId(),session);
        }catch (NullPointerException e){
            e.printStackTrace();
        }
    }
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        out.println("websocket 收到消息: " + message.getPayload());
        try{
            User user = (User) session.getAttributes().get("user");
            MessageRequest req=objectMapper.readValue(message.getPayload(),MessageRequest.class);
            if ("message".equals(req.getType())){
                handleMessage(user,req);
            }
        }catch (NullPointerException e){
            e.printStackTrace();
        }
    }


    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        out.println("websocket 连接断开!");
        try{
            User user = (User) session.getAttributes().get("user");
            onlineUserManager.offline(user.getId(),session);
        }catch (NullPointerException e){
            e.printStackTrace();
        }
    }
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        out.println("websocket 连接异常!");
        try{
            User user = (User) session.getAttributes().get("user");
            onlineUserManager.offline(user.getId(),session);
        }catch (NullPointerException e){
            e.printStackTrace();
        }
    }

    private void handleMessage(User fromUser, MessageRequest req) throws IOException {
        MessageResponse resp=new MessageResponse();
        resp.setType("message");
        resp.setFromId(fromUser.getId());
        resp.setFromName(fromUser.getUsername());
        resp.setSessionId(req.getSessionId());
        resp.setContent(req.getContent());
        resp.setPostTime(new Timestamp(currentTimeMillis()));
        String respJson=objectMapper.writeValueAsString(resp);
        out.println("[handlerMassage] resp:"+respJson);
//        根据相关请求在数据库中查询相关所有的id
        List<Friend> friends=messageSessionMapper.getFriendsBySessionId(req.getSessionId(), fromUser.getId());
//        把自己也加入到这个列表中
        Friend myself=new Friend();
        myself.setId(fromUser.getId());
        myself.setFriendName(fromUser.getUsername());
        friends.add(myself);
        out.println("[handlerMessage] 要转发给哪些人:"+friends);
//        根据每个人的用户id,找到对应的WebsocketSession,并进行发送数据.
        for (Friend friend : friends) {
            WebSocketSession  webSocketSession=onlineUserManager.getSession(friend.getId());
            if(webSocketSession==null){
                continue;
            }
            webSocketSession.sendMessage(new TextMessage(respJson));
        }
//        把消息写入数据库
        Message message=new Message();
        message.setFromId(resp.getFromId());
        message.setSessionId(resp.getSessionId());
        message.setContent(resp.getContent());
        message.setPostTime(resp.getPostTime());
        messageMapper.add(message);

    }

}
